package com.sxz.sbs.module.client;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nanchen.compresshelper.CompressHelper;
import com.sxz.sbs.R;
import com.sxz.sbs.applibrary.KeyBordStateUtil;
import com.sxz.sbs.applibrary.component.ClearEditText;
import com.sxz.sbs.applibrary.dialog.input.ValueInputBoardDialog;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.client.bean.ClientDetailsBean;
import com.sxz.sbs.module.client.bean.ContractTypeBean;
import com.sxz.sbs.module.client.bean.SelectStallBean;
import com.sxz.sbs.module.client.presenter.DealEvidencePresenter;
import com.sxz.sbs.module.client.qr.CaptureActivity;
import com.sxz.sbs.module.client.view.DealEvidenceView;
import com.sxz.sbs.module.photo.PhotoViewerActivity;
import com.sxz.sbs.module.photo.PhotoViewerBean;
import com.sxz.sbs.module.sale.mode.ImgBackBean;
import com.sxz.sbs.module.staff.AllParkingActivity;
import com.sxz.sbs.other.FileBean;
import com.sxz.sbs.other.ImageShowAdapter;
import com.sxz.sbs.view.SelfAdaptionGridView;
import com.sxz.sbs.widget.CommonTitle;
import com.tian.photopicker.PhotoPicker;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @author hp
 * @date 2018/1/12
 * 上传成交凭证
 */

public class DealEvidenceActivity extends BaseActivity<DealEvidencePresenter> implements DealEvidenceView {

    @BindView(R.id.gridView)
    SelfAdaptionGridView gridView;
    @BindView(R.id.tv_bargain_xq)
    TextView tvBargainXq;
    @BindView(R.id.tv_bargain_stall)
    TextView tvBargainStall;
    @BindView(R.id.tv_bargain_stall_type)
    TextView tvBargainStallType;
    @BindView(R.id.tv_bargain_stall_area)
    TextView tvBargainStallArea;
    @BindView(R.id.tv_bargain_stall_money)
    TextView tvBargainStallMoney;
    @BindView(R.id.cet_add_1)
    ClearEditText cetAdd1;
    @BindView(R.id.cet_add_2)
    TextView cetAdd2;
    @BindView(R.id.cet_add_3)
    TextView cetAdd3;

    private ImageShowAdapter adapter;
    private List<FileBean> fileList = new ArrayList<>();
    private  List<String> urlList = new ArrayList<>();
    private List<ContractTypeBean> dataCompact = new ArrayList<>();
    private OptionsPickerView compactPicker;
    /**
     * 合同ID
     */
    private int compactId;
    private ClientDetailsBean intentBean;
    private String price = "";
    private int parkingId;
    private String stallId;
    private ProgressDialog progressDialog;
    private int deleteIndex;
    private KeyBordStateUtil keyBordStateUtil;
    private boolean isQuestContact ;
    @Override
    protected void init() {
        new CommonTitle.Builder(this).setTitle("上传成交凭证").build().show();
        intentBean = getIntent().getParcelableExtra("deal_evidence");
        keyBordStateUtil = new KeyBordStateUtil(this);
        keyBordStateUtil.addOnKeyBordStateListener(mOnKeyBordStateListener);
        if (intentBean != null) {
            tvBargainXq.setText(intentBean.getParkingName());
            parkingId = intentBean.getParking_Id();
        }
        adapter = new ImageShowAdapter(this, fileList, 9);
        gridView.setAdapter(adapter);
        adapter.setOnImageShowListener(new ImageShowAdapter.OnImageShowListener() {
            @Override
            public void onImageClick(View v, int position) {
                urlList.clear();
                for (int i = 0; i < fileList.size(); i++) {
                    if (fileList.get(i) != null) {
                        urlList.add(fileList.get(i).getPath());
                    }
                }
                PhotoViewerBean pvb = new PhotoViewerBean(urlList,position) ;
                startActivity(new Intent(DealEvidenceActivity.this, PhotoViewerActivity.class)
                        .putExtra(PhotoViewerActivity.PHOTO_VIEWER_TAG, pvb));
            }

            @Override
            public void onImageDelete(View v, int position) {
                deleteIndex = position;
                HashMap<String,Object> map = HttpParamMap.getParamMap();
                map.put("fileId",fileList.get(position).getId());
                mPresenter.deletePhoto(map);
            }

            @Override
            public void onImageAdd(View v, int position) {
                PhotoPicker.builder().setSelectPhotoCount(9 - (fileList.size() - 1)).
                        start(DealEvidenceActivity.this, 1000);
            }
        });
    }
    private KeyBordStateUtil.onKeyBordStateListener mOnKeyBordStateListener = new KeyBordStateUtil.onKeyBordStateListener() {
        @Override
        public void onSoftKeyBoardShow(int keyboardHeight) {

        }
        @Override
        public void onSoftKeyBoardHide() {
            if (!TextUtils.isEmpty(cetAdd1.getText().toString())) {
                isQuestContact = true;
                HashMap<String,Object> map = HttpParamMap.getParamMap();
                map.put("number",cetAdd1.getText().toString());
                mPresenter.getContractType(map);
            }
        }
    };
    @Override
    protected int getLayoutId() {
        return R.layout.activity_dealevidence;
    }

    @Override
    protected DealEvidencePresenter createPresenter() {
        return new DealEvidencePresenter();
    }

    /**
     * 初始化合同选择
     */
    private void initCompactPicker() {
        compactPicker = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                if (dataCompact!=null && dataCompact.size()>0){
                    cetAdd2.setText(dataCompact.get(options1).getName());
                    compactId = dataCompact.get(options1).getId();
                    cetAdd3.setText(dataCompact.get(options1).getPage()+"");
                }else {
                    ToastUtils.showShort("该合同类型未找到,请联系管理员!");
                }

            }
        }).build();
        compactPicker.setPicker(dataCompact);
        compactPicker.show();
    }


    /**
     * 点击事件处理
     *
     * @param view
     */
    @OnClick({R.id.rl_bargain_xq, R.id.rl_bargain_stall, R.id.tv_bargain_stall_money,R.id.iv_scan, R.id.cet_add_2, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_bargain_xq:
                startActivityForResult(new Intent(this, AllParkingActivity.class)
                        .putExtra("from_tag",5)
                ,1002);
                break;
            case R.id.iv_scan:
                PermissionUtils.permission(PermissionConstants.CAMERA, PermissionConstants.STORAGE)
                        .callback(new PermissionUtils.SimpleCallback() {
                            @Override
                            public void onGranted() {
                                startActivityForResult(new Intent(DealEvidenceActivity.this,CaptureActivity.class),1004);
                            }
                            @Override
                            public void onDenied() {
                                ToastUtils.showShort("请授予照相机等相关权限");
                            }
                        }).request();

                break;
            case R.id.rl_bargain_stall:
                startActivityForResult(new Intent(this, SelectStallActivity.class)
                                .putExtra("customId",intentBean.getId())
                                .putExtra("parkingId",parkingId)
                                .putExtra("root_in",2)
                        ,1003);
                break;
            case R.id.tv_bargain_stall_money:
                ValueInputBoardDialog dialog1 = new ValueInputBoardDialog(this,price,ValueInputBoardDialog.UnitEnum.SELL);
                dialog1.setOnDialogResultListener(new ValueInputBoardDialog.OnDialogResultListener() {
                    @Override
                    public void onResult(String value, String unit) {
                        price = value;
                        tvBargainStallMoney.setText(value + unit);
                    }
                });
                dialog1.show();
                break;
            case R.id.cet_add_2:
                if (compactPicker != null) {
                    compactPicker.show();
                } else {
                    mPresenter.getContractTypeList(HttpParamMap.getParamMap());
                }
                break;
            case R.id.submit:
                if (stallId == null) {
                    ToastUtils.showShort("请选择车位");
                    return;
                }
                if (TextUtils.isEmpty(tvBargainStallMoney.getText().toString())) {
                    ToastUtils.showShort("售价不能为空");
                    return;
                }
                if (TextUtils.isEmpty(cetAdd1.getInputValue())) {
                    ToastUtils.showShort("合同编号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(cetAdd2.getText().toString())) {
                    ToastUtils.showShort("合同类型不能为空");
                    return;
                }
                if (TextUtils.isEmpty(cetAdd3.getText().toString())) {
                    ToastUtils.showShort("合同页数不能为空");
                    return;
                }
                if (fileList.size() <= 1) {
                    ToastUtils.showShort("请选择合同照片");
                    return;
                }
                /*if (fileList.size()< 9) {
                    fileList.remove(fileList.size()-1);
                }*/
                String urlString = "";
                for (int i = 0; i < fileList.size(); i++) {
                    if (fileList.get(i) != null) {
                        urlString = urlString + fileList.get(i).getId()+",";
                    }
                }
                urlString = urlString.substring(0,urlString.length()-1);
                HashMap<String,Object> map = HttpParamMap.getParamMap();
                map.put("customId",intentBean.getId());
                map.put("spaceId",stallId);
                map.put("money",price);
                map.put("photoId",urlString);
                map.put("valType",compactId);
                map.put("txtNumber",cetAdd1.getInputValue());
                map.put("pageCount",cetAdd3.getText().toString());
                mPresenter.uploadDealEvidence(map);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (requestCode == 1000) {
            List<String> result = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            progressDialog = ProgressDialog.show(this, null, "上传中...");
            List<File> fileList = new ArrayList<>();
            for (int i = 0; i < result.size(); i++) {
                if (result.get(i) != null) {
                    File newFile = new CompressHelper.Builder(this)
                            .setMaxWidth(720)
                            .setMaxHeight(1080)
                            .setQuality(90)
                            .setFileName(System.currentTimeMillis()+""+i)
                            .setCompressFormat(Bitmap.CompressFormat.JPEG)
                            .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                                    Environment.DIRECTORY_PICTURES).getAbsolutePath())
                            .build()
                            .compressToFile(new File(result.get(i)));
                    if (newFile != null) {
                        fileList.add(newFile);
                    }
                }
            }
            List<MultipartBody.Part> map = filesToMultipartBodyParts(fileList);
            mPresenter.uploadPhoto(2,map);


        } else if (requestCode == 1002 && resultCode == 1006) {
            parkingId = data.getIntExtra("parking_id",0);
            tvBargainXq.setText(data.getStringExtra("parking_name"));
        } else if (requestCode == 1003 && resultCode == 1007) {
            SelectStallBean.ListBean bean = data.getParcelableExtra("stall_result");
            if (bean != null) {
                tvBargainStall.setText(TextUtils.isEmpty(bean.getNumber())?"无":bean.getNumber());
                tvBargainStallType.setText(bean.getSpaceTypeName()+"");
                tvBargainStallArea.setText(bean.getSize()+"㎡");
                stallId = bean.getId()+"";
            }
        } else if (requestCode == 1004) {
            String result = data.getStringExtra("result_code");
            if (!TextUtils.isEmpty(result)) {
                cetAdd1.setText(result);
                cetAdd1.setSelection(cetAdd1.getInputValue().length());
                isQuestContact = true;
                HashMap<String,Object> map = HttpParamMap.getParamMap();
                map.put("number",result);
                mPresenter.getContractType(map);
            }
        }
    }
    @Override
    public void onUploadEvidenceSuccess() {
        ToastUtils.showShort("上传成功");
        finish();
    }

    @Override
    public void onUploadFileSuccess(List<ImgBackBean> data) {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        if (mIsLive && data != null) {
            fileList.remove(fileList.size()-1);
            for (int i = 0; i < data.size(); i++) {
                fileList.add(new FileBean(data.get(i).getId(),data.get(i).getPhotoUrl()));
            }
            adapter.setNotify(fileList);
        }
    }

    @Override
    public void showError(int errorTag, String msg) {
        super.showError(errorTag, msg);
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
       /* if (isQuestContact) {
            isQuestContact = false;
            cetAdd1.clearText();
            cetAdd3.setText("");
            cetAdd2.setText("");
            compactId = 0;
        }*/

    }

    @Override
    public void onDeleteFileSuccess() {
        fileList.remove(deleteIndex);
        adapter.setNotify(fileList);
    }

    @Override
    public void onGetContractTypeList(List<ContractTypeBean> data) {
        if (mIsLive && data != null) {
            dataCompact.clear();
            dataCompact.addAll(data);
            initCompactPicker();
        }

    }

    @Override
    public void onGetContractType(ContractTypeBean data) {
        if (mIsLive && data !=null) {
            cetAdd2.setText(data.getName());
            compactId = data.getId();
            cetAdd3.setText(data.getPage()+"");
        }
    }

    public  List<MultipartBody.Part> filesToMultipartBodyParts(List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        int i = 1;
        for (File file : files) {
            i++;
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("fileList"+i, file.getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }
}
